package com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.RxRegistrationChargeCategory;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.RxRegistrationPlanChargeCategorySetting;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryDetailResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryRecordResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.mapper.RxRegistrationChargeCategoryMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.mapper.RxRegistrationPlanChargeCategorySettingMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.RxRegistrationAdvanceStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.resp.RxRegistrationAdvanceStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.mapper.RxRegistrationAdvanceStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.RxRegistrationWelcomeDelay;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.RxRegistrationWelcomeReduction;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.req.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationPlanChargeCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationStudentInfoReduceCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationWelcomeReductionResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.mapper.RxRegistrationWelcomeDelayMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.mapper.RxRegistrationWelcomeReductionMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.service.RxRegistrationWelcomeReductionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.util.WelcomeStuUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.resp.SmsUserResp;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_DONE;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.ChargeCategoryTypeConstant.CHARGE_CATEGORY_TYPE_NORMAL;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.AllowStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.AllowStatusConstant.ALLOW_STATUS_DENY;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.ApplyConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.signUp.constant.SmsSignUpCommonConstant.PER_SHEET_NUM;

/**
 * <p>
 * 招生管理学生减免申请表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-05-16
 */
@Service
public class RxRegistrationWelcomeReductionServiceImpl extends ServiceImpl<RxRegistrationWelcomeReductionMapper, RxRegistrationWelcomeReduction> implements RxRegistrationWelcomeReductionService {

    @Resource
    private RxRegistrationWelcomeReductionMapper rxRegistrationWelcomeReductionMapper;
    @Resource
    private RxRegistrationAdvanceStudentInfoMapper rxRegistrationAdvanceStudentInfoMapper;
    @Resource
    private SmsUserMapper smsUserMapper;
    @Resource
    private WelcomeStuUtil welcomeStuUtil;
    @Resource
    private ApiModelUtil apiModelUtil;
    @Resource
    private SmsImportTaskMapper smsImportTaskMapper;
    @Resource
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private RxRegistrationPlanChargeCategorySettingMapper rxRegistrationPlanChargeCategorySettingMapper;
    @Resource
    private RxRegistrationWelcomeDelayMapper rxRegistrationWelcomeDelayMapper;
    @Resource
    private RxRegistrationChargeCategoryMapper rxRegistrationChargeCategoryMapper;


    @Override
    @Transactional
    public ResponseResult addRegistrationWelcomeReduction(RxRegistrationWelcomeReductionReq addReq) {
        if (isNullOrEmpty(addReq.getStuId(), addReq.getIdCard(), addReq.getApplicationReason(), addReq.getReductionAmount())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<RxRegistrationWelcomeReduction> delayList = rxRegistrationWelcomeReductionMapper.selectList(new LambdaQueryWrapper<RxRegistrationWelcomeReduction>()
                .eq(RxRegistrationWelcomeReduction::getStuId, addReq.getStuId()));
        //缓交和缓交不允许同时提交
        List<RxRegistrationWelcomeDelay> welcomeDelayList = rxRegistrationWelcomeDelayMapper.selectList(new LambdaQueryWrapper<RxRegistrationWelcomeDelay>()
                .eq(RxRegistrationWelcomeDelay::getStuId, addReq.getStuId()));
        if (welcomeDelayList != null && welcomeDelayList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_REDUCE_AND_DELAY_NOT_SUBMIT);
        }

        //校验申请情况
        if (delayList != null && delayList.size() > 0) {
            List<Integer> allowStatusList = delayList.stream().map(RxRegistrationWelcomeReduction::getAllowStatus).collect(Collectors.toList());
            //学生提交申请 通过后不允许提交
            if (allowStatusList.contains(ALLOW_STATUS_PASS)) {
                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_APPLY_EXIT_PASS);
            }
            //校验学生有待审批申请下 不可再次提交
            if (allowStatusList.contains(ALLOW_STATUS_WAIT_ALLOW)) {
                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_EXIT_ALLOW);
            }
        }

        //校验学生
        String stuId = addReq.getStuId();
        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(stuId);
        if (isNullOrEmpty(studentInfo)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT);
        }
        studentInfo.setReductionStatus(APPLY_STATUS_WAIT_ALLOW);
        rxRegistrationAdvanceStudentInfoMapper.updateById(studentInfo);
        //创建申请表
        RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction = new RxRegistrationWelcomeReduction();
        BeanUtils.copyProperties(addReq, rxRegistrationWelcomeReduction);
        rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_WAIT_ALLOW);
        rxRegistrationWelcomeReductionMapper.insert(rxRegistrationWelcomeReduction);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getRegistrationWelcomeReductionList(Integer pageNum, Integer pageSize, String stuName, String idCard, Integer allowStatus) {
        Page<RxRegistrationWelcomeReduction> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<RxRegistrationWelcomeReduction> reductionLambdaQueryWrapper = new LambdaQueryWrapper<RxRegistrationWelcomeReduction>()
                .orderByDesc(RxRegistrationWelcomeReduction::getCreateTime);
        if (!isNullOrEmpty(stuName)) {
            reductionLambdaQueryWrapper.like(RxRegistrationWelcomeReduction::getName, stuName);
        }
        if (!isNullOrEmpty(idCard)) {
            reductionLambdaQueryWrapper.like(RxRegistrationWelcomeReduction::getIdCard, idCard);
        }
        if (!isNullOrEmpty(allowStatus)) {
            reductionLambdaQueryWrapper.eq(RxRegistrationWelcomeReduction::getAllowStatus, allowStatus);
        }
        rxRegistrationWelcomeReductionMapper.selectPage(page, reductionLambdaQueryWrapper);
        List<RxRegistrationWelcomeReductionResp> reductionRespList = page.getRecords()
                .stream().map(reduction -> {
                    RxRegistrationWelcomeReductionResp reductionResp = new RxRegistrationWelcomeReductionResp();
                    BeanUtils.copyProperties(reduction, reductionResp);
                    return reductionResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(reductionRespList, (int)page.getTotal());
    }

    @Override
    public ResponseResult getRegistrationWelcomeReductionDetail(String applyId) {
        if (isNullOrEmpty(applyId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction = rxRegistrationWelcomeReductionMapper.selectById(applyId);
        if (isNullOrEmpty(rxRegistrationWelcomeReduction)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_REDUCTION_NOT_EXIT);
        }
        RxRegistrationWelcomeReductionResp reductionResp = new RxRegistrationWelcomeReductionResp();
        BeanUtils.copyProperties(rxRegistrationWelcomeReduction,reductionResp);
        //学生信息
        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(rxRegistrationWelcomeReduction.getStuId());
        if (isNullOrEmpty(studentInfo)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT);
        }
        RxRegistrationAdvanceStudentInfoResp resp = welcomeStuUtil.getWelcomeAllStuPaymentCategory(studentInfo);
        List<RxRegistrationPlanChargeCategoryResp> chargeCategoryRecordRespList = resp.getChargeCategoryRespList();

        if (chargeCategoryRecordRespList != null) {
            reductionResp.setBeforeCategoryList(chargeCategoryRecordRespList);
        }

        String reductionCategory = rxRegistrationWelcomeReduction.getReductionCategory();
        if (!isNullOrEmpty(reductionCategory)) {
            List<RxRegistrationPlanChargeCategoryResp> chargeCategorySettingReqList =
                    JSON.parseArray(reductionCategory, RxRegistrationPlanChargeCategoryResp.class);
            reductionResp.setAfterCategoryList(chargeCategorySettingReqList);
        }

        if (!isNullOrEmpty(rxRegistrationWelcomeReduction.getAllowUserId())) {
            SmsUser smsUser = smsUserMapper.selectById(rxRegistrationWelcomeReduction.getAllowUserId());
            if (!isNullOrEmpty(smsUser)) {
                SmsUserResp allowUserInfo = new SmsUserResp();
                BeanUtils.copyProperties(smsUser, allowUserInfo);
                reductionResp.setAllowUserInfo(allowUserInfo);
            }
        }
        return CommonResult.success(reductionResp);
    }

    @Override
    @Transactional
    public ResponseResult allowRegistrationWelcomeReduction(RxRegistrationWelcomeDelayAllowReq allowReq, String user_id) {
        if (isNullOrEmpty(allowReq.getApplyId(), allowReq.getAllowStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //申请表
        RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction = rxRegistrationWelcomeReductionMapper.selectById(allowReq.getApplyId());
        if (isNullOrEmpty(rxRegistrationWelcomeReduction)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_REDUCTION_NOT_EXIT);
        }
        //学生信息
        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(allowReq.getStuId());
        if (isNullOrEmpty(studentInfo)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT);
        }
        //审批状态只能是通过和驳回
        Integer allowStatus = allowReq.getAllowStatus();
        if (allowStatus != ALLOW_STATUS_PASS && allowStatus != ALLOW_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //驳回时修改学生减免和申请表的状态
        if (allowStatus == ALLOW_STATUS_DENY) {
            rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_DENY);
            rxRegistrationWelcomeReduction.setAllowOption(allowReq.getAllowOption());
            rxRegistrationWelcomeReduction.setAllowTime(new Date());
            rxRegistrationWelcomeReduction.setAllowUserId(user_id);

            studentInfo.setReductionStatus(ALLOW_STATUS_DENY);
        } else {//通过时需导入学生减免后的缴费清单
            List<RxRegistrationPlanChargeCategoryResp> categoryList = allowReq.getCategoryList();
            if (categoryList == null || categoryList.size() == 0) {
                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_NOT_EXIT);
            }
            //原始缴费项
            RxRegistrationAdvanceStudentInfoResp resp = welcomeStuUtil.getWelcomeAllStuPaymentCategory(studentInfo);
            List<RxRegistrationPlanChargeCategoryResp> welcomeStuPaymentCategory = resp.getChargeCategoryRespList();
            if (welcomeStuPaymentCategory == null) {
                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_NOT_EXIT);
            }
            if (welcomeStuPaymentCategory.size() != categoryList.size()) {
                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_AMOUNT_INCONFORMITY);
            }
            for (RxRegistrationPlanChargeCategoryResp categorySettingReq : categoryList) {
                if (categorySettingReq.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_NORMAL) {
                    //必填
                    if (isNullOrEmpty(categorySettingReq.getChargeCategoryName(), categorySettingReq.getChargeCategoryId(),
                            categorySettingReq.getChargeCategoryPrice())) {
                        return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
                    }
                    //金额不能小于0
                    BigDecimal chargeCategoryPrice = categorySettingReq.getChargeCategoryPrice();
                    if (chargeCategoryPrice.compareTo(BigDecimal.ZERO) < 0) {
                        return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_AMOUNT_INCONFORMITY);
                    }
                } else {
                    List<RxRegistrationChargeCategoryDetailResp> childList = categorySettingReq.getChildList();
                    for (RxRegistrationChargeCategoryDetailResp categoryDetailResp : childList) {
                        if (isNullOrEmpty(categoryDetailResp.getChargeCategoryName(), categoryDetailResp.getChargeCategoryId(),
                                categoryDetailResp.getChargeCategoryPrice())) {
                            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
                        }
                        //金额不能小于0
                        BigDecimal chargeCategoryPrice = categoryDetailResp.getChargeCategoryPrice();
                        if (chargeCategoryPrice.compareTo(BigDecimal.ZERO) < 0) {
                            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_AMOUNT_INCONFORMITY);
                        }
                    }

                }


            }
            String categoryJson = JSON.parseObject(JSON.toJSONString(categoryList), String.class);
            rxRegistrationWelcomeReduction.setReductionCategory(categoryJson);
            //修改学生减免和申请表状态
            rxRegistrationWelcomeReduction.setAllowOption(allowReq.getAllowOption());
            rxRegistrationWelcomeReduction.setAllowTime(new Date());
            rxRegistrationWelcomeReduction.setAllowUserId(user_id);
            rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_PASS);

            studentInfo.setReductionStatus(ALLOW_STATUS_PASS);
        }
        rxRegistrationWelcomeReductionMapper.updateById(rxRegistrationWelcomeReduction);
        rxRegistrationAdvanceStudentInfoMapper.updateById(studentInfo);
        return CommonResult.success();
    }

//    @Override
//    @Async
//    public Future<ResponseResult> exportStuShouldPaymentCategory(RxRegistrationAdvanceStudentInfoReduceExportReq exportReq, HttpServletResponse response) {
//
//        try {
//            //构造导出数据
//            RxRegistrationStudentInfoReduceCategoryResp list = new RxRegistrationStudentInfoReduceCategoryResp();
//
//            if (isNullOrEmpty(exportReq.getStuId())) {
//                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
//            }
//            RxRegistrationAdvanceStudentInfo rxRegistrationAdvanceStudentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(exportReq.getStuId());
//            if (isNullOrEmpty(rxRegistrationAdvanceStudentInfo)) {
//                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT));
//            }
//            //学生姓名 id
//            list.setStuId(exportReq.getStuId());
//            list.setName(rxRegistrationAdvanceStudentInfo.getName());
//            //学生收费项
//            RxRegistrationAdvanceStudentInfoResp resp = welcomeStuUtil.getWelcomeAllStuPaymentCategory(rxRegistrationAdvanceStudentInfo.getIdCard());
//            List<RxRegistrationPlanChargeCategoryResp> welcomeStuPaymentCategory = resp.getChargeCategoryRespList();
//            if (welcomeStuPaymentCategory == null) {
//                return new AsyncResult<>(CommonResult.success(list));
//            }
//
//            List<RxRegistrationPlanChargeCategoryResp> categoryList = welcomeStuPaymentCategory
//                    .stream()
//                    .map(chargeCategoryResp -> {
//                        RxRegistrationPlanChargeCategoryResp resp1 = new RxRegistrationPlanChargeCategoryResp();
//                        BeanUtils.copyProperties(chargeCategoryResp, resp1);
//                        return resp1;
//                    })
//                    .collect(Collectors.toList());
//            list.setChargeCategoryList(categoryList);
//
//            //表头数据
////            String[] header = exportReq.getLimitColumn().toArray(new String[0]);
//            double sheetNum;
//            //声明一个工作簿
//            HSSFWorkbook workbook = new HSSFWorkbook();
//            sheetNum = Math.ceil((double) 1 / PER_SHEET_NUM);
//            for (int k = 0; k < sheetNum; k++) {
//                //生成一个表格，设置表格名称为"资源导出表"
//                HSSFSheet sheet = workbook.createSheet("学生缴费信息导出表" + (k + 1));
//
//                //设置表格列宽度为10个字节
//                sheet.setDefaultColumnWidth(12);
//                //创建标题的显示样式
//                HSSFCellStyle headerStyle = workbook.createCellStyle();
//                headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
//                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//
//                HSSFFont f = workbook.createFont();
//                f.setFontHeightInPoints((short) 10);//字号
//                f.setBold(true);//加粗
//                headerStyle.setFont(f);
//                //创建第一行表头
//                HSSFRow remarkRow = sheet.createRow(0);
//                remarkRow.setHeightInPoints((float) 40.0);
//                Cell remarkCell = remarkRow.createCell(0); // A1 单元格
//                remarkCell.setCellValue("1:学生姓名、学生id、缴费项id、缴费项名称不可修改\n"
//                        + "2:缴费项金额修改只能（大于0）并且（小于或者等于）原始金额");
//
//                // 合并A1到D1四个单元格
//                int numColumnsToMerge = 5; // 要合并的列数
//                CellRangeAddress region = new CellRangeAddress(
//                        0, // 起始行索引
//                        0, // 结束行索引
//                        0, // 起始列索引
//                        numColumnsToMerge - 1); // 结束列索引
//                sheet.addMergedRegion(region);
//
//                CellStyle style = workbook.createCellStyle();
//                style.setWrapText(true);//换行
//                style.setAlignment(HorizontalAlignment.LEFT); // 水平左对齐
//                style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
//                remarkCell.setCellStyle(style);
//                //创建第一行表头
//                HSSFRow headRow = sheet.createRow(1);
//
//                //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
//                List<RxRegistrationPlanChargeCategoryResp> chargeCategoryList = list.getChargeCategoryList();
//                int columnNum = chargeCategoryList.size() + 2;
//                //收费项
//                for (int i = 0; i < columnNum; i++) {
//                    //创建一个单元格
//                    String columnName = "";
//                    switch (i) {
//                        case 0:
//                            columnName = "学生姓名";
//                            break;
//                        case 1:
//                            columnName = "学生身份证";
//                            break;
//                        default:
//                            for (int j = 0; j < 2; j++) {
//                                if (j == 0) {
//                                    columnName = chargeCategoryList.get(i - 2).getChargeCategoryId();
//                                }else {
//                                    columnName = chargeCategoryList.get(i - 2).getChargeCategoryName();
//                                }
//
//
//                            }
//
//                    }
//                    HSSFCell cell = headRow.createCell(i);
//                    cell.setCellStyle(headerStyle);
//                    //创建一个内容对象
//                    HSSFRichTextString text = new HSSFRichTextString(columnName);
//                    //将内容对象的文字内容写入到单元格中
//                    cell.setCellValue(text);
//
//                }
//
//                //创建一行
//                HSSFRow row = sheet.createRow(2);
//                for (int i = 0; i < columnNum; i++) {
//                    String data = "";
//                    switch (i) {
//                        case 0:
//                            data = rxRegistrationAdvanceStudentInfo.getName();
//                            break;
//                        case 1:
//                            data = rxRegistrationAdvanceStudentInfo.getName();
//                            break;
//                        default:
//                            for (int j = 0; j < 2; j++) {
//                                if (j == 0) {
//                                    data = chargeCategoryList.get(i - 2).getChargeCategoryId();
//                                } else {
//                                    data = chargeCategoryList.get(i - 2).getChargeCategoryPrice().toString();
//                                }
//                            }
//                    }
//                    row.createCell(i).setCellValue(new HSSFRichTextString(data == null ? "" : data));
//                }
//            }
//
//
//
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("学生缴费信息导出表.xlsx", "utf-8"));
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("file-type", "download");
//            response.setHeader("file-name", URLEncoder.encode("学生缴费信息导出表.xlsx", "utf-8"));
//            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
//            response.flushBuffer();
//            //workbook将Excel写入到response的输出流中，供页面下载
//            OutputStream os = response.getOutputStream();
//            workbook.write(os);
//
//            workbook.close();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
//        }
//        return null;
//    }

    @Override
    @Async
    public Future<ResponseResult> allowRegistrationWelcomeReduction1(RxRegistrationWelcomeDelayAllowReq allowReq, String userId) {
        if (isNullOrEmpty(allowReq.getApplyId(), allowReq.getAllowStatus())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        //开启事务
        DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
        // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
        dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        // 设置嵌套事务
        TransactionStatus status = transactionManager.getTransaction(dt);
        try {
            //申请表
            RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction = rxRegistrationWelcomeReductionMapper.selectById(allowReq.getApplyId());
            if (isNullOrEmpty(rxRegistrationWelcomeReduction)) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_REDUCTION_NOT_EXIT));
            }
            //学生信息
            RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(allowReq.getStuId());
            if (isNullOrEmpty(studentInfo)) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT));
            }
            //审批状态只能是通过和驳回
            Integer allowStatus = allowReq.getAllowStatus();
            if (allowStatus != ALLOW_STATUS_PASS && allowStatus != ALLOW_STATUS_DENY) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            //驳回时修改学生减免和申请表的状态
            if (allowStatus == ALLOW_STATUS_DENY) {
                rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_DENY);
                studentInfo.setReductionStatus(ALLOW_STATUS_DENY);
            } else {//通过时需导入学生减免后的缴费清单
//                List<RxRegistrationWelcomeChargeCategorySettingReq> categoryList = allowReq.getCategoryList();
//                if (categoryList == null || categoryList.size() == 0) {
//                    return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_CATEGORY_NOT_EXIT));
//                }
//                //创建导入任务
//                SmsImportTask smsImportTask = new SmsImportTask();
//                smsImportTask.setTaskName(TASK_NAME_STUDENT_CATEGORY_IMPORT);
//                smsImportTask.setUserId(userId);
//                smsImportTask.setTaskType(TASK_TYPE_REGISTRATION_STUDENT_CATEGORY_IMPORT);
//                smsImportTaskMapper.insert(smsImportTask);
//                batchAddStuShouldPaymentCategory(allowReq,rxRegistrationWelcomeReduction, smsImportTask.getId(), userId);
//                //修改学生减免和申请表状态
//                rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_PASS);
//                studentInfo.setReductionStatus(ALLOW_STATUS_PASS);
            }
            rxRegistrationWelcomeReductionMapper.updateById(rxRegistrationWelcomeReduction);
            rxRegistrationAdvanceStudentInfoMapper.updateById(studentInfo);
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        } finally {
            if (status.isNewTransaction() && !status.isCompleted()) {
                transactionManager.commit(status);
            }
        }
        return new AsyncResult<>(CommonResult.success());
    }

    private void batchAddStuShouldPaymentCategory(RxRegistrationWelcomeDelayAllowReq allowReq,RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction,String id, String userId) {
        int OFFSET_ROW = 2;
        int task_status = TASK_STATUS_DONE;

//
//        List<RxRegistrationWelcomeChargeCategorySettingReq> categoryList = allowReq.getCategoryList();
//        for (int i = 0; i < categoryList.size(); i++) {
//            //开启事务
//            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
//            // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
//            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
//            // 设置嵌套事务
//            TransactionStatus status = transactionManager.getTransaction(dt);
//            RxRegistrationWelcomeChargeCategorySettingReq categorySettingReq = categoryList.get(i);
//            try {
//                //必填
//                if (isNullOrEmpty(categorySettingReq.getChargeCategoryName(), categorySettingReq.getChargeCategoryId(),
//                        categorySettingReq.getChargeCategoryPrice())) {
//                    transactionManager.rollback(status);
//                    task_status = TASK_STATUS_ERR;
//                    createTeacherImportTaskDetail(id, REASON_INVALID_PARAM, (OFFSET_ROW) + "");
//                }
//                //金额不能小于0
//                BigDecimal chargeCategoryPrice = categorySettingReq.getChargeCategoryPrice();
//                if (chargeCategoryPrice.compareTo(BigDecimal.ZERO) < 0) {
//                    transactionManager.rollback(status);
//                    task_status = TASK_STATUS_ERR;
//                    createTeacherImportTaskDetail(id, REASON_AMOUNT_LIST_NOT_EXIST, (OFFSET_ROW) + "");
//                }
//                //查询收费项
//                RxRegistrationPlanChargeCategorySetting chargeCategorySetting = rxRegistrationPlanChargeCategorySettingMapper.selectById(categorySettingReq.getChargeCategoryId());
//                if (isNullOrEmpty(chargeCategorySetting)) {
//                    transactionManager.rollback(status);
//                    task_status = TASK_STATUS_ERR;
//                    createTeacherImportTaskDetail(id, REASON_REGISTRATION_CATEGORY_NOT_EXIST, (OFFSET_ROW) + "");
//                }
//                transactionManager.commit(status);
//            } catch (Exception e) {
//                transactionManager.rollback(status);
//                task_status = TASK_STATUS_ERR;
//                createTeacherImportTaskDetail(id, REASON_IMPORT_ERR, (OFFSET_ROW) + "");
//            } finally {
//                if (status.isNewTransaction() && !status.isCompleted()) {
//                    transactionManager.commit(status);
//                }
//            }
//        }
//        String categoryJson = JSON.parseObject(JSON.toJSONString(categoryList), String.class);
//        rxRegistrationWelcomeReduction.setReductionCategory(categoryJson);

        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setId(id);
        smsImportTask.setStatus(task_status);
        smsImportTaskMapper.updateById(smsImportTask);
    }

    private void createTeacherImportTaskDetail(String id, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(id);
        smsImportTaskDetail.setFailReason(reason);
        smsImportTaskDetail.setFailRow(row);
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }

    @Override
    public ResponseResult getMyApply(String stuId) {
        if (isNullOrEmpty(stuId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<RxRegistrationWelcomeReductionResp> reductionList = rxRegistrationWelcomeReductionMapper.selectList(
                new LambdaQueryWrapper<RxRegistrationWelcomeReduction>()
                        .eq(RxRegistrationWelcomeReduction::getStuId, stuId)
                        .orderByDesc(RxRegistrationWelcomeReduction::getCreateTime))
                .stream()
                .map(reduction -> {
                    RxRegistrationWelcomeReductionResp reductionResp = new RxRegistrationWelcomeReductionResp();
                    BeanUtils.copyProperties(reduction, reductionResp);
                    return reductionResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(reductionList);
    }

    @Override
    @Transactional
    public ResponseResult cancelRegistrationWelcomeReduction(RxRegistrationWelcomeReductionReq cancelReq) {
        if (isNullOrEmpty(cancelReq.getApplyId(),cancelReq.getStuId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        RxRegistrationWelcomeReduction rxRegistrationWelcomeReduction = rxRegistrationWelcomeReductionMapper.selectById(cancelReq.getApplyId());
        if (isNullOrEmpty(rxRegistrationWelcomeReduction)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_REDUCTION_NOT_EXIT);
        }
        rxRegistrationWelcomeReduction.setAllowStatus(ALLOW_STATUS_CANCEL);
        rxRegistrationWelcomeReductionMapper.updateById(rxRegistrationWelcomeReduction);
        //修改学生缓交状态
        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(cancelReq.getStuId());
        if (isNullOrEmpty(studentInfo)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT);
        }
        studentInfo.setDelayStatus(APPLY_STATUS_CANCEL);
        rxRegistrationAdvanceStudentInfoMapper.updateById(studentInfo);
        return CommonResult.success();
    }


}
